package com.pri.chat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.WishMsgActivity;
import com.netease.nim.uikit.net.entity.WishListBean;
import com.pri.chat.adapter.WishAdapter;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.model.UserModel;
import com.pri.chat.model.WishModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.netease.nim.uikit.net.SharedHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.FragmentLazy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class WishDoneFragment extends FragmentLazy implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    Unbinder unbinder;
    private List<WishListBean> mList;
    private WishAdapter mAdapter;
    private int type;
    private int page = 1;
    private boolean isShowDialog = false;

    public static WishDoneFragment getInstance(int type) {
        WishDoneFragment fragment = new WishDoneFragment();
        fragment.type = type;
        return fragment;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }
    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_wish_list_layout, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        srlAll.setEnableLoadmore(false);
        initLayout();
        initSrl();
        return view;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if(messageEvent.getTag().equals(EventTag.WISH)){
            refresh();
        }
    }
    private void initLayout() {
        mList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new WishAdapter(R.layout.item_wish, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnImageClickListener(new WishAdapter.OnImageClickListener() {
            @Override
            public void onItemClick(View view, int c_pos, int f_pos) {
                PictureSelector.create(mContext)
                        .themeStyle(R.style.picture_default_style)
                        .isNotPreviewDownload(true)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
            }
        });

    }

    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<WishListBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                RxToast.normal(getString(R.string.no_data));
            } else {
                none.setVisibility(View.INVISIBLE);
                for(int i=0;i<baseBean.getData().size();i++){
                    if(type==1){
                        if(baseBean.getData().get(i).getStatus()!=2){
                            mList.add(baseBean.getData().get(i));
                        }
                    }else {
                        if(baseBean.getData().get(i).getStatus()==2){
                            mList.add(baseBean.getData().get(i));
                        }
                    }

                }
                if (mList.isEmpty() && page == 1) {
                    none.setVisibility(View.VISIBLE);
//                    mAdapter.notifyDataSetChanged();
                    RxToast.normal(getString(R.string.no_data));
                }
                for (int i = 0; i < mList.size(); i++) {
                    String[] imgs = mList.get(i).getPicList().split(",");
                    List<String> list = new ArrayList<>();
                    List<LocalMedia> mediaList = new ArrayList<>();
                    for (int j = 0; j < imgs.length; j++) {
                        LocalMedia localMedia = new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
            }
        };
        UserModel dtModel = new UserModel();//登录上传参数
        dtModel.setMemberId(SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().listWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    private void refresh() {
        page=1;
        isShowDialog=false;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.tv_wish_go:
                httpGoWish(position);
                break;
            case R.id.iv_logo:
                Bundle bundle =new Bundle();
                bundle.putString("id",mList.get(position).getMemberId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                break;
            case R.id.iv_share:
                break;
        }
    }

    private void httpGoWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("接收愿望成功");
//            srlAll.autoRefresh();
        };
        WishModel dtModel = new WishModel(0);
        dtModel.setMemberId(SharedHelper.readId(mContext));
        dtModel.setWishId(mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().saveWishHelp(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(mContext, WishMsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("wish", mList.get(position));
        bundle_2.putInt("position",position);
        intent.putExtras(bundle_2);
        startActivityForResult(intent, 0x10);
    }
}
